package com.blockmeta.bbs.overallserviceapplication.web;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.baselibrary.utils.NetworkStateUtil;
import com.blockmeta.bbs.baselibrary.utils.SecurityUtil;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.Jsbridge.MyJsBridge;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.eventbus.MsgSuccess;
import com.blockmeta.bbs.businesslibrary.umeng.ShareRouter;
import com.blockmeta.bbs.businesslibrary.umeng.ShareType;
import com.blockmeta.bbs.businesslibrary.umeng.TypeDescribe;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.DeviceUtil;
import com.blockmeta.bbs.businesslibrary.widget.WebViewContainer;
import com.blockmeta.bbs.overallserviceapplication.R;
import com.blockmeta.bbs.overallserviceapplication.R2;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = RouterPath.WEB_ACTIVITY)
public class WebActivity extends BaseActivity {

    @BindView(R2.id.center_title)
    TextView mCenterTitle;
    @BindView(R2.id.webview)
    WebViewContainer m_webContainer;
    private View mRootView;

    @Autowired(name = Constant.ZERO)
    public String url;

    private String mTitle = "网页分享";

    private ShareRouter mShareRouter;
    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        if (null == mRootView)
        {
            mRootView = LayoutInflater.from(mContext).inflate(R.layout.activity_web, null);
            initView(mRootView);
        }

        reFresh();
        return mRootView;
    }

    private void initView(View tView)
    {
        m_webContainer = (WebViewContainer) tView.findViewById(R.id.webview);
        m_webContainer.setColorSchemeResources(R.color.sys_swipe_progress_color);
        m_webContainer.setRefreshEnable(false);
        m_webContainer.setWebviewListener(new WebViewContainer.WebviewListener() {
            @Override
            public void onPageStart(WebView webView, String url) {

            }

            @Override
            public void onTitleReceived(String title) {
                if(!TextUtils.isEmpty(title)) {
                    mTitle = title;
                    mCenterTitle.setText(title);
                }
            }

            @Override
            public boolean onShouldOverrideUrl(String url) {
                LogUtils.d("sss", "shouldOverrideUrlLoading: "+url);
                if (url.startsWith("http")||url.startsWith("https")) {
                    m_webContainer.synCookies(WebActivity.this , url, "");
                    m_webContainer.load(url);
                    if ("bbt8.8btc.com".equals(Uri.parse(url).getHost())){
                        finish();
                    }
                }else if (url.startsWith("btc8outside")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url.replace("btc8outside", "http").trim()));
                    if (intent.resolveActivity(mContext.getPackageManager()) != null) {
                        startActivity(intent);
                    }
                } else if (url.startsWith("btc8share")) {
                    //友盟自定义事件统计（链接分享）
                    MobclickAgent.onEvent(mContext, Constant.INVITE_LINK);
                    setShare(url);
                }else {
                    Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    if (in.resolveActivity(getPackageManager())==null) {return false;}
                    startActivity(in);
                }
                return true;
            }
        });
        m_webContainer.setZoomEnable(false);
        HashMap<String, WebViewContainer.JavascriptInterface> jsMap = new HashMap<>();
        jsMap.put("chaininterface", new WebViewContainer.JavascriptInterface() {
            @Override
            public Object createJsInterface(Context context) {
                return new MyJsBridge(context);
            }
        });
        m_webContainer.addJsInterfaces(jsMap);
    }

    private void reFresh()
    {

        if (! NetworkStateUtil.isNetWorkAvailable(WebActivity.this))
        {
            m_webContainer.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }

        if (! url.equals(m_webContainer.getUrl()))
        {
            m_webContainer.synCookies(this , url, "");
            m_webContainer.load(url);
        }

    }

    @Override
    public void onBackPressed()
    {
        goBack();
    }

    private void goBack() {

        if (m_webContainer != null && m_webContainer.goBack())
        {
        }else {
            finish();
        }
    }

    @Override
    protected void initialize() {
        super.initialize();

    }

    private void setShare(String url) {
        String shareUrl = url.replace("btc8share://", "http://");
        Uri shareUri = Uri.parse(Uri.decode(shareUrl));
        String title = shareUri.getQueryParameter("title");
        String desc = shareUri.getQueryParameter("desc");

        if (mShareRouter == null){
            mShareRouter = new ShareRouter.Builder()
                    .context(mContext)
                    .shareType(ShareType.NORMAL_WEB)
                    .typeDescribe(TypeDescribe.ACTIVITY)
                    .url(shareUrl)
                    .title(title)
                    .describe(desc)
                    .umShareListener(mUMShareListener)
                    .build();
        }
        mShareRouter.show();
    }

    private void inputJs() {
        m_webContainer.callJavaScript("shareCb", null);
        //需要重新LoadUrl
        reFresh();
    }

    UMShareListener mUMShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA share_media) {
            inputJs();
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {

        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {

        }
    };


    @OnClick({R2.id.left_back,R2.id.right_share})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.left_back) {
            goBack();
        }else if (id == R.id.right_share){
            callSystemShare();
        }
    }
    private void callSystemShare(){
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        String content = "我正在看【"+mTitle+"】分享给你一起看吧！"+url;
        sendIntent.putExtra(Intent.EXTRA_TEXT, content);
        sendIntent.setType("text/plain");

        Intent shareIntent = Intent.createChooser(sendIntent, null);
        startActivity(shareIntent);
    }
    @Override
    protected void onDestroy() {
        try {
            m_webContainer.getWebView().destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();

    }

}
